<template>
  <div style="padding-top: 10px;background-color: #ffffff">
    <!-- 表单 -->
    <el-form :inline="true" :model="page" class="demo-form-inline" style="margin-right: 800px;white-space: nowrap">
      <el-form-item label="">
        <el-input v-model="page.queryString" placeholder="姓名/性别"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="onSubmit">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" icon="el-icon-refresh" @click="replaseMent">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="type">
      <el-table :data="tableData" :pagination="false" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column fixed type="selection" width="50%" align="center" />
        <el-table-column prop="id" label="编号" width="60" align="center"></el-table-column>
        <el-table-column prop="name" label="姓名" width="180" align="center"></el-table-column>
        <el-table-column prop="username" label="账号" width="180" align="center"></el-table-column>
        <el-table-column prop="sex" label="性别" width="140" align="center">
          <template v-slot="scope">
            <span>{{ scope.row.sex === 1 ? '男' : '女' }}</span>
          </template>
        </el-table-column>
        <!--<el-table-column prop="image" label="图像" width="180"></el-table-column>-->
        <el-table-column prop="imageUrl" label="图像" width="140" align="center">
          <template v-slot="{ row }">
            <img :src="row.imageUrl" width="100px" height="70px">
          </template>
        </el-table-column>
        <el-table-column prop="isdelete" label="状态" width="180" align="center">
          <template v-slot="scope">
            <el-switch
              v-model="switchValueMain[scope.$index]"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="1"
              inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
              @change="handleChangeTypeAd(scope.row.id,scope.row.isdelete)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮件" width="200" align="center"></el-table-column>
        <el-table-column prop="phone" label="电话号码" width="140" align="center"></el-table-column>
<!--        <el-table-column el-table-column fixed="right" label="操作" width="200" align="center">-->
<!--          <template v-slot="scope">-->
<!--            <el-button type="primary" size="mini" icon="el-icon-paperclip" @click="handleUpdate(scope.row)">编辑</el-button>-->
<!--            <el-popconfirm-->
<!--              title="这是一段内容确定删除吗？"-->
<!--              icon="el-icon-info"-->
<!--              icon-color="red"-->
<!--              @confirm="deleteItem(scope.row)"-->
<!--              style="margin-left: 5px;white-space: nowrap"-->
<!--            >-->
<!--              <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini">删除</el-button>-->
<!--            </el-popconfirm>-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>
    </div>
    <!--   添加 -->
    <div>
      <el-dialog v-bind="$attrs" :visible.sync="addDialogFormVisible" title="添加用户" :modal="false" :width="'40%'">
        <el-row :gutter="15">
          <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
            <el-col :span="10">
              <el-form-item label="单行文本" prop="field101">
                <el-input v-model="formData.field101" placeholder="请输入单行文本单行文本" clearable
                          :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="单行文本" prop="field102">
                <el-input v-model="formData.field102" placeholder="请输入单行文本" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="单行文本" prop="field103">
                <el-input v-model="formData.field103" placeholder="请输入单行文本" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="单行文本" prop="field104">
                <el-input v-model="formData.field104" placeholder="请输入单行文本" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="单行文本" prop="field111">
                <el-input v-model="formData.field111" placeholder="请输入单行文本" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="单行文本" prop="field112">
                <el-input v-model="formData.field112" placeholder="请输入单行文本" clearable :style="{width: '100%'}">
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <div class="custom-upload-container">
                <div class="upload-title">头像上传</div>
                <el-upload
                  class="avatar-uploader"
                  action="http://127.0.0.1:8888/user/image/userImage"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload">
                  <img v-if="imageUrl" :src="imageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </div>
            </el-col>
            <el-col :span="20">
              <el-form-item label="多行文本" prop="field115">
                <el-input v-model="formData.field115" type="textarea" placeholder="请输入多行文本"
                          :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item label="多行文本" prop="field116">
                <el-input v-model="formData.field116" type="textarea" placeholder="请输入多行文本"
                          :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
        <div slot="footer">
          <el-button @click="addDialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="addDialogUser">确定</el-button>
        </div>
      </el-dialog>
    </div>
    <!--分页-->
    <div style="text-align: right;padding: 10px 20px;" >
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentPageChange"
        :current-page="page.page"
        :page-sizes="[5, 10, 15, 25, 30]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total" />
    </div>
    <el-dialog :visible.sync="dialogFormVisible" title="编辑弹框" :modal="false" :width="'40%'">
      <el-row :gutter="15">
        <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px">
          <el-col :span="11">
            <el-form-item label="单行文本" prop="name">
              <el-input v-model="formData.name" placeholder="请输入单行文本" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="单行文本" prop="username">
              <el-input v-model="formData.username" placeholder="请输入单行文本" disabled="disabled" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="下拉选择" prop="sex">
              <el-select v-model="formData.sex" placeholder="请选择下拉选择" clearable :style="{width: '100%'}">
                <!-- 注意：el-option 设置了 value 属性 -->
                <el-option v-for="(item, index) in sex" :key="index" :label="getLabel(item)" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="单行文本" prop="password">
              <el-input v-model="formData.password" placeholder="请输入单行文本" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="单行文本" prop="email">
              <el-input v-model="formData.email" placeholder="请输入单行文本" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="单行文本" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入单行文本" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="单行文本" prop="license">
              <el-input v-model="formData.license" placeholder="请输入单行文本" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <div class="custom-upload-container">
              <div class="upload-title">头像上传</div>
              <el-upload
                class="avatar-uploader"
                action="http://127.0.0.1:8888/userImage"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
          </el-col>
          <el-col :span="22">
            <el-form-item label="多行文本" prop="prescriptionRecords">
              <el-input v-model="formData.prescriptionRecords" type="textarea" placeholder="请输入多行文本"
                        :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="多行文本" prop="medicalHistory">
              <el-input v-model="formData.medicalHistory" type="textarea" placeholder="请输入多行文本"
                        :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleEdit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import zhCn from 'element-ui/lib/locale/lang/zh-CN'
import request from '../../api/request'
import { adminInfo } from '@/api/user'

export default {
  data () {
    return {
      switchValueMain: [],
      locale: zhCn,
      sexModel: '',
      dataList: [], // 当前页要展示的分页列表数据
      dialogFormVisible: false,
      addDialogFormVisible: false,
      visible: false,
      formLabelWidth: '120px',
      tableData: [],
      form: [],
      imageUrl: '',
      page: {
        total: 10,
        currentPage: 1,
        pageSize: 5,
        queryString: ''
      },
      originalQueryString: '',
      formData: {
        sex: '',
        imageUrl: ''
      },
      sex: [
        { value: 1, label: '男' },
        { value: 0, label: '女' }
      ],
      rules: []
    }
  },
  components: {
  },
  props: [],
  created () {
    this.getData()
  },
  computed: {
  },
  methods: {
    getLabel (item) {
      // 这个函数应该根据数据库的值返回对应的标签，例如 "男" 或 "女"
      if (item.value === 1) {
        return '男'
      } else {
        return '女'
      }
    },
    // 修改状态
    handleChangeTypeAd (val, isdelete) {
      this.$confirm('此操作将禁用或启用该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {
          id: val,
          isdelete: (isdelete === 1 ? 0 : 1)
        }
        request.put('/user/updataClientUesrStatus', data, {
          headers: {
            accept: 'application/json',
            Authorization: 'Bearer ' + localStorage.getItem('token')
          }
        }).then((resp) => {
          if (resp.data.flag === true) {
            /// alert(this.switchValueMain)
            this.$message({
              message: resp.data.message,
              type: 'success',
              offset: 80,
              center: true
            })
            this.getData()
            return
          }
          this.$message({
            message: resp.data.message,
            type: 'error',
            offset: 80,
            center: true
          })
          this.getData()
        }).catch(err => {
          this.handleAxiosError(err)
          this.getData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消',
          offset: 80,
          center: true
        })
        this.getData()
      })
    },
    handleUpdate (row) {
      this.dialogFormVisible = true
      const data = this.$cookies.get('rememberMe')
      const token = data.token
      const _this = this
      request.get('/user/' + row.id, { headers: { Authorization: `Bearer ${token}` } }).then((resp) => {
        _this.formData = resp.data.data // Assuming the response contains user data
      })
    },
    handleEdit () {
    },
    addUserInfo () {
      this.addDialogFormVisible = true
      this.formData = []
    },
    // 添加
    addDialogUser () {
    },
    onSubmit () {
      this.page.currentPage = 1
      this.getData()
    },
    replaseMent () {
      this.page.queryString = ''
      this.getData()
    },
    async getData () {
      // alert(this.page.queryString)
      // if (this.page.queryString === '启用') {
      //   this.originalQueryString = 1
      // }
      // if (this.page.queryString === '禁用') {
      //   this.originalQueryString = 0
      // }
      const infoData = {
        currentPage: this.page.currentPage,
        pageSize: this.page.pageSize,
        queryString: this.page.queryString
      }
      try {
        await adminInfo(infoData).then(resp => {
          const data = resp.data
          this.page.total = data.total
          this.tableData = data.rows
          this.switchValueMain = data.rows.map(item => String(item.isdelete))
          this.originalQueryString = ''
          // alert(this.switchValue)
        })
      } catch (error) {
        this.handleAxiosError(error)
      }
    },
    deleteItem (row) {
      const data = this.$cookies.get('rememberMe')
      const token = data.token
      request.delete('/user/' + row.id, { headers: { Authorization: `Bearer ${token}` } }).then(resp => {
        if (resp.data.flag) {
          this.visible = false
          this.$message({
            type: 'success',
            message: resp.data.message
          })
        }
        this.getData()
      })
    },
    handlePageSizeChange (pageSize) {
      this.page.pageSize = pageSize
      this.page.currentPage = 1 // 重置为第一页
      this.getData()
    },
    handleCurrentPageChange (currentPage) {
      this.page.currentPage = currentPage
      this.getData()
    },
    handleAvatarSuccess (res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      this.imageUrl = res.data
      this.formData.imageUrl = res.data
    },
    beforeAvatarUpload (file) {
      const allowedFormats = ['image/jpeg', 'image/png', 'image/gif'] // 允许的文件格式

      const isAllowedFormat = allowedFormats.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isAllowedFormat) {
        this.$message.error('上传头像图片只能是 JPG、PNG 或 GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isAllowedFormat && isLt2M
    },
    handleSelectionChange () {},
    handleAxiosError (error) {
      // 检查是否是Axios的网络错误
      if (error.isAxiosError && error.response) {
        // 处理您的网络错误，例如显示用户友好的提示
        this.$message({
          message: '网络请求失败，发生错误，请稍后重试',
          type: 'error',
          offset: 80,
          center: true
        })
      } else {
        // 处理其他类型的错误
        this.$message({
          message: '网络请求失败，请稍后重试',
          type: 'error',
          offset: 80,
          center: true
        })
      }
    }
  }
}
</script>

<style scoped>
/*@import "../../assets/css/style.css";*/
.avatar-uploader .el-upload {
  border: 1px dashed #d97979;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border: 1px dashed #409EFF; /* 修改为:hover时的边框颜色 */
}

.avatar-uploader-icon {
  font-size: 25px;
  color: #2667c4;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #bcbebf;
  margin: 20px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.custom-upload-container {
  display: flex;
  align-items: center;
  margin-left: 25px;
}

.upload-title {
  margin-left: 10px;
  white-space: nowrap;
}
</style>
